package com.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dao.dao.IGoodsDao;
import com.dao.dao.IUserDao;
import com.dao.entity.Goods;
import com.dao.entity.User;
import com.dao.redis.IRedislLoginVerifyDao;
import com.net.base.BaseResponse;
import com.net.filter.LoginFilter;
import com.util.Contants;
import com.util.NetUtil;
import com.util.Utils;

/**
 * 文件处理控制器
 * 
 * @author 尚业
 *
 */
@Controller
@RequestMapping(value = "/file")
public class FileHandleController {
	private static Logger logger = Logger.getLogger(LoginFilter.class);

	@Autowired
	IGoodsDao goodsDao;

	@Autowired
	IRedislLoginVerifyDao redislLoginVerifyDao;
	
	@Autowired
	IUserDao userDao;
	
	/**
	 * 上传头像
	 * 
	 * @param request
	 * @param headPhotoFile
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uploadHead")
	@ResponseBody
	public BaseResponse<User> uploadHeadPhone(HttpServletRequest request ,@RequestParam("img") MultipartFile headPhotoFile)
			throws IOException {
		String userName=Utils.getUserNameBytaken(redislLoginVerifyDao,request.getHeader("JSESSIONID"));
		if(userName==null){
			return NetUtil.getCommonFailuerResponse("会话过期");
		}
		if (headPhotoFile.isEmpty()) {
			logger.warn("没有图片信息");
			return NetUtil.getCommonFailuerResponse("没有图片信息");
		} else {
			String contentType = headPhotoFile.getContentType();
			if (contentType.startsWith("image")) {
				// 获取真实路径
				String realPath = System.getProperty("root");
				String host=Utils.getApplicationProperties().getProperty("applicationHost");
				String newFileName = new Date().getTime() + "" + new Random().nextInt() + ".jpg";
				realPath =realPath+Contants.PATH_IMAGE+userName+"/"+newFileName;
				logger.warn(realPath);
				File file = new File(realPath);
				FileUtils.copyInputStreamToFile(headPhotoFile.getInputStream(), file);
				
				String url=host+Contants.PATH_IMAGE+userName+"/"+newFileName;
				//有老图片就删除
				User user=userDao.selectByUserName(userName);
				String oldPhoto=user.getHeadImage();
				
				if (oldPhoto!=null&&!NetUtil.deleteFileByUrl(oldPhoto)) {
					file.delete();
					return NetUtil.getCommonFailuerResponse("删除头像图片失败");
				}
				
				user.setHeadImage(url);
				int flag = userDao.updateByUserNameSelective(user);
				if (flag != 0 && flag != -1) {
					return NetUtil.getCommonSuccessResponse("请求成功");
				} else {
					file.delete();
					return NetUtil.getCommonFailuerResponse("请求失败");
				}
			} else {
				return NetUtil.getCommonFailuerResponse("上传了不支持的文件类型");
			}
		}
	}
	
	/**
	 * 上传图片和物品信息
	 * 
	 * @param headPhotoFile
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uploadGoods")
	@ResponseBody
	public BaseResponse<Goods> uploadGoods(HttpServletRequest request ,@RequestParam("img") MultipartFile headPhotoFile)
			throws IOException {
		String userName=Utils.getUserNameBytaken(redislLoginVerifyDao,request.getHeader("JSESSIONID"));
		if(userName==null){
			return NetUtil.getCommonFailuerResponse("会话过期");
		}
		if (headPhotoFile.isEmpty()) {
			logger.warn("没有图片信息");
			return NetUtil.getCommonFailuerResponse("没有图片信息");
		} else {
			String contentType = headPhotoFile.getContentType();
			if (contentType.startsWith("image")) {
				// 获取真实路径
				String realPath = request.getSession().getServletContext().getRealPath("/");
				String host=Utils.getApplicationProperties().getProperty("applicationHost");
				String absolutePath = "image/"+userName+"/";
				String newFileName = new Date().getTime() + "" + new Random().nextInt() + ".jpg";
				absolutePath+=newFileName;
				logger.warn(realPath+absolutePath);
				File file = new File(realPath+absolutePath);
				FileUtils.copyInputStreamToFile(headPhotoFile.getInputStream(), file);
				
				String url=host+absolutePath;
				//添加货物到数据库
				Goods goods = new Goods();
				goods.setUsername(request.getParameter("username"));
				goods.setGoodsname(request.getParameter("goodsname"));
				goods.setGoodssort(request.getParameter("goodssort"));
				goods.setImage(url);
				goods.setNum(Integer.valueOf(request.getParameter("num")));
				goods.setPrice(Double.valueOf(request.getParameter("price")));
				goods.setGoodsdescribe(request.getParameter("goodsdescribe"));
				goods.setSellcount(0);
				int flag = goodsDao.insert(goods);
				if (flag != 0 && flag != -1) {
					return NetUtil.getCommonSuccessResponse("请求成功");
				} else {
					file.delete();
					return NetUtil.getCommonFailuerResponse("请求失败");
				}
			} else {
				return NetUtil.getCommonFailuerResponse("上传了不支持的文件类型");
			}
		}
	}

	/**
	 * 下载图片信息
	 * 
	 * @param request
	 * @param response
	 * @param goodsId
	 * @return
	 * @throws Exception
	 */
//	@RequestMapping("/download")
//	@ResponseBody
//	public String download(HttpServletRequest request, HttpServletResponse response, int goodsId)
//			throws Exception {
//
//		Goods goods=goodsDao.selectByPrimaryKey(goodsId);
//		if(goods==null){
//			return null;
//		}
//		
//		String path = goods.getImage();
//		File file = new File(path);
//		response.setCharacterEncoding("UTF-8");
//		response.setContentLength((int) file.length());
//		int len = 0;
//		byte[] buffer = new byte[1024];
//		InputStream is = new FileInputStream(file);
//		OutputStream os = response.getOutputStream();
//		while ((len = is.read(buffer)) != -1) {
//			os.write(buffer, 0, len);
//		}
//		is.close();
//		os.close();
//		return null; 
//	}

}
